<template>
  <div class="direct-evaluations-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-select
              v-model="searchForm.academicYear"
              placeholder="学年筛选"
              clearable
              @change="handleSearch"
              style="width: 120px"
            >
              <el-option
                v-for="year in academicYears"
                :key="year"
                :label="year"
                :value="year"
              />
            </el-select>

            <el-select
              v-model="searchForm.semester"
              placeholder="学期筛选"
              clearable
              @change="handleSearch"
              style="width: 100px"
            >
              <el-option label="第一学期" :value="1" />
              <el-option label="第二学期" :value="2" />
            </el-select>

            <el-select
              v-model="searchForm.courseId"
              placeholder="课程筛选"
              clearable
              filterable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.courseName"
                :value="course.id"
              />
            </el-select>

            <el-select
              v-model="searchForm.indicatorId"
              placeholder="指标点筛选"
              clearable
              filterable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="indicator in indicators"
                :key="indicator.id"
                :label="indicator.indicatorName"
                :value="indicator.id"
              />
            </el-select>

            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>

          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin || userStore.isTeacher || userStore.isMajorLeader"
          >
            新增评价
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="evaluations"
        border
        style="width: 100%"
      >
        <el-table-column prop="academicYear" label="学年" width="80" />
        <el-table-column prop="semester" label="学期" width="80">
          <template #default="{ row }">
            {{ row.semester === 1 ? '第一学期' : '第二学期' }}
          </template>
        </el-table-column>
        <el-table-column prop="courseName" label="课程名称" min-width="120" />
        <el-table-column prop="indicatorName" label="指标点名称" min-width="120" />
        <el-table-column prop="evaluationScore" label="直接评价分数" width="120">
          <template #default="{ row }">
            {{ formatNumber(row.evaluationScore, 4) }}
          </template>
        </el-table-column>
        <el-table-column prop="studentCount" label="参与评价学生数" width="120" />
        <el-table-column prop="avgScore" label="课程平均分" width="100">
          <template #default="{ row }">
            {{ formatNumber(row.avgScore, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="passRate" label="达标率(%)" width="100">
          <template #default="{ row }">
            {{ formatPercent(row.passRate, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="goalAchievement" label="课程目标达成度" width="120">
          <template #default="{ row }">
            {{ formatNumber(row.goalAchievement, 4) }}
          </template>
        </el-table-column>
        <el-table-column prop="supportWeight" label="支撑权重" width="100">
          <template #default="{ row }">
            {{ formatNumber(row.supportWeight, 4) }}
          </template>
        </el-table-column>
        <el-table-column prop="evaluatorName" label="评价人" width="100" />
        <el-table-column prop="evaluationTime" label="评价时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.evaluationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="dataSource" label="数据来源" width="100" />
        <el-table-column prop="evaluationStatus" label="评价状态" width="100" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin || userStore.isTeacher || userStore.isMajorLeader"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin || userStore.isMajorLeader"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评价表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增直接评价' : '编辑直接评价'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="学年" prop="academicYear">
          <el-select v-model="form.academicYear" placeholder="请选择学年" style="width: 100%">
            <el-option
              v-for="year in academicYears"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择学期" style="width: 100%">
            <el-option label="第一学期" :value="1" />
            <el-option label="第二学期" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程" filterable style="width: 100%">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.courseName"
              :value="course.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="指标点" prop="indicatorId">
          <el-select v-model="form.indicatorId" placeholder="请选择指标点" filterable style="width: 100%">
            <el-option
              v-for="indicator in indicators"
              :key="indicator.id"
              :label="indicator.indicatorName"
              :value="indicator.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="评价人" prop="evaluatorId">
          <el-select v-model="form.evaluatorId" placeholder="请选择评价人" filterable style="width: 100%">
            <el-option
              v-for="teacher in teachers"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="评价时间" prop="evaluationTime">
          <el-date-picker
            v-model="form.evaluationTime"
            type="datetime"
            placeholder="请选择评价时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="数据来源" prop="dataSource">
          <el-select v-model="form.dataSource" placeholder="请选择数据来源" style="width: 100%">
            <el-option
              v-for="option in dataSourceOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="评价状态" prop="evaluationStatus">
          <el-select v-model="form.evaluationStatus" placeholder="请选择评价状态" style="width: 100%">
            <el-option
              v-for="option in evaluationStatusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>

        <!-- 以下字段为只读，由后端计算后返回 -->
        <el-form-item label="直接评价分数">
          <el-input :value="formatNumber(form.evaluationScore, 4)" readonly />
        </el-form-item>
        <el-form-item label="参与评价学生数">
          <el-input :value="form.studentCount" readonly />
        </el-form-item>
        <el-form-item label="课程平均分">
          <el-input :value="formatNumber(form.avgScore, 2)" readonly />
        </el-form-item>
        <el-form-item label="达标率(%)">
          <el-input :value="formatPercent(form.passRate, 2)" readonly />
        </el-form-item>
        <el-form-item label="课程目标达成度">
          <el-input :value="formatNumber(form.goalAchievement, 4)" readonly />
        </el-form-item>
        <el-form-item label="支撑权重">
          <el-input :value="formatNumber(form.supportWeight, 4)" readonly />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const evaluations = ref([])
const courses = ref([])
const indicators = ref([])
const teachers = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 生成最近10年的学年选项
const academicYears = computed(() => {
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = 0; i < 10; i++) {
    years.push(currentYear - i)
  }
  return years
})

const searchForm = reactive({
  academicYear: null,
  semester: null,
  courseId: null,
  indicatorId: null
})

const form = reactive({
  id: null,
  courseId: null,
  indicatorId: null,
  evaluationScore: null,
  academicYear: null,
  semester: null,
  studentCount: 0,
  avgScore: null,
  passRate: null,
  goalAchievement: null,
  supportWeight: null,
  evaluatorId: null,
  evaluationTime: null,
  dataSource: '课程考核',
  evaluationStatus: '初稿',
  remark: ''
})

const rules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  indicatorId: [{ required: true, message: '请选择指标点', trigger: 'change' }],
  academicYear: [{ required: true, message: '请选择学年', trigger: 'change' }],
  semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
  evaluatorId: [{ required: true, message: '请选择评价人', trigger: 'change' }],
  evaluationTime: [{ required: true, message: '请选择评价时间', trigger: 'change' }],
  dataSource: [{ required: true, message: '请选择数据来源', trigger: 'change' }],
  evaluationStatus: [{ required: true, message: '请选择评价状态', trigger: 'change' }]
}

const dataSourceOptions = [
  { value: '课程考核', label: '课程考核' },
  { value: '作业', label: '作业' },
  { value: '实践', label: '实践' }
]

const evaluationStatusOptions = [
  { value: '初稿', label: '初稿' },
  { value: '审核中', label: '审核中' },
  { value: '已确认', label: '已确认' }
]

const fetchEvaluations = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/direct-evaluations/page', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        academicYear: searchForm.academicYear,
        semester: searchForm.semester,
        courseId: searchForm.courseId,
        indicatorId: searchForm.indicatorId
      }
    })
    evaluations.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取评价列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchCourses = async () => {
  try {
    const res = await request.get('/api/courses')
    courses.value = res.data
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

const fetchIndicators = async () => {
  try {
    const res = await request.get('/api/indicators')
    indicators.value = res.data
  } catch (error) {
    console.error('获取指标点列表失败:', error)
  }
}

const fetchTeachers = async () => {
  try {
    const res = await request.get('/api/teachers')
    teachers.value = res.data
  } catch (error) {
    console.error('获取教师列表失败:', error)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchEvaluations()
}

const resetSearch = () => {
  searchForm.academicYear = null
  searchForm.semester = null
  searchForm.courseId = null
  searchForm.indicatorId = null
  currentPage.value = 1
  fetchEvaluations()
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    courseId: row.courseId,
    indicatorId: row.indicatorId,
    evaluationScore: row.evaluationScore,
    academicYear: row.academicYear,
    semester: row.semester,
    studentCount: row.studentCount,
    avgScore: row.avgScore,
    passRate: row.passRate,
    goalAchievement: row.goalAchievement,
    supportWeight: row.supportWeight,
    evaluatorId: row.evaluatorId,
    evaluationTime: row.evaluationTime ? new Date(row.evaluationTime) : null,
    dataSource: row.dataSource,
    evaluationStatus: row.evaluationStatus,
    remark: row.remark
  })
  dialogVisible.value = true
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该评价记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await request.delete(`/api/direct-evaluations/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchEvaluations()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const dataToSend = { ...form }
    
    if (dataToSend.evaluationTime) {
      if (dataToSend.evaluationTime instanceof Date) {
        dataToSend.evaluationTime = dataToSend.evaluationTime.toISOString().slice(0, 19).replace('T', ' ')
      } else if (typeof dataToSend.evaluationTime === 'string') {
        const date = new Date(dataToSend.evaluationTime)
        if (!isNaN(date.getTime())) {
          dataToSend.evaluationTime = date.toISOString().slice(0, 19).replace('T', ' ')
        } else {
          ElMessage.error('评价时间格式不正确')
          return
        }
      }
    }

    if (dataToSend.id) {
      const response = await request.put(`/api/direct-evaluations/${dataToSend.id}`, dataToSend)
      if (response.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchEvaluations()
      } else {
        ElMessage.error(response.msg || '更新失败')
      }
    } else {
      const response = await request.post('/api/direct-evaluations', dataToSend)
      if (response.code === 200) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        fetchEvaluations()
      } else {
        ElMessage.error(response.msg || '创建失败')
      }
    }
  } catch (error) {
    console.error('提交错误:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(error.response.data.message || '操作失败')
    } else {
      ElMessage.error('操作失败: ' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    courseId: null,
    indicatorId: null,
    evaluationScore: null,
    academicYear: null,
    semester: null,
    studentCount: 0,
    avgScore: null,
    passRate: null,
    goalAchievement: null,
    supportWeight: null,
    evaluatorId: null,
    evaluationTime: null,
    dataSource: '课程考核',
    evaluationStatus: '初稿',
    remark: ''
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEvaluations()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEvaluations()
}

const formatDateTime = (value) => {
  if (!value) return '-'
  const date = new Date(value)
  return date.toLocaleString()
}

const formatNumber = (value, decimals = 2) => {
  if (value == null) return '-'
  return Number(value).toFixed(decimals)
}

const formatPercent = (value, decimals = 2) => {
  if (value == null) return '-'
  return `${Number(value).toFixed(decimals)}%`
}

onMounted(async () => {
  await Promise.all([
    fetchEvaluations(),
    fetchCourses(),
    fetchIndicators(),
    fetchTeachers()
  ])
})
</script>

<style scoped>
.direct-evaluations-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 